<script setup lang="ts">
import { onMounted, onUnmounted, watch, ref, computed, getCurrentInstance } from 'vue'
import { useSettingsStore } from '@/store/theme';
import { useThemeStore } from '@/store/theme';
import { userStore } from '@/store/user';
import { ElTooltip } from 'element-plus';
import { init, dispose, registerFigure, registerOverlay } from 'klinecharts'
import { registerIndicatorMa, registerIndicatorEma, registerIndicatoVol, registerIndicatoMacd } from '@/hooks/index'
import { query } from '@/apis/currency'
import { useCoinStore } from '@/store/coin'
import TootipOrdinary from './kline/TootipOrdinary.vue';
import TootipMA from './kline/TootipMA.vue';
import TootipEMA from './kline/TootipEMA.vue';
import TootipVOL from './kline/TootipVOL.vue';
import { formatNumberWithThousands, getFloorPeriodTimestamps } from '../utils/utils';

registerFigure({
  name: 'diamond',
  draw: (ctx, attrs, styles) => {
    const { x, y, size, baseY } = attrs; // baseY：目标基准点Y坐标（如K线价格位置）
    const {
      text = 'B',
      bgColor = text === 'B' ? '#2dbd85' : '#f6475d',
      textColor = '#ffffff',
      cornerRadius = size * 0.25,
      offsetB = -size * 0.3, // B的偏移量（远离目标值）
      offsetS = -size * 1.5, // S的偏移量（靠近目标值）
      leftOffset = size * 0.5, // 整体左移偏移量
      arrowSize = size * 0.2 // 箭头大小（B和S共用）
    } = styles;

    // 计算左移后的基准X坐标
    const adjustedX = x - leftOffset;

    // 计算实际绘制的Y坐标（根据B/S动态偏移，预留箭头位置）
    let drawY;
    if (text === 'B') {
      // B点：向上偏移，预留上方箭头位置（图形下移，箭头在上方）
      drawY = baseY - offsetB + arrowSize;
    } else {
      // S点：向下偏移，预留下方箭头位置（图形上移，箭头在下方）
      drawY = baseY + offsetS - arrowSize;
    }

    // 绘制对应方向的箭头
    if (text === 'B') {
      // B点：上方箭头（向上指向）
      const arrowX = adjustedX + size / 2; // 水平居中
      const arrowY = drawY; // 箭头底部与图形顶部对齐

      ctx.beginPath();
      ctx.moveTo(arrowX - arrowSize, arrowY); // 左点
      ctx.lineTo(arrowX + arrowSize, arrowY); // 右点
      ctx.lineTo(arrowX, arrowY - arrowSize); // 上顶点（指向baseY）
      ctx.closePath();
    } else {
      // S点：下方箭头（向下指向）
      const arrowX = adjustedX + size / 2; // 水平居中
      const arrowY = drawY + size; // 箭头顶部与图形底部对齐

      ctx.beginPath();
      ctx.moveTo(arrowX - arrowSize, arrowY); // 左点
      ctx.lineTo(arrowX + arrowSize, arrowY); // 右点
      ctx.lineTo(arrowX, arrowY + arrowSize); // 下顶点（指向baseY）
      ctx.closePath();
    }
    // 箭头填充与背景同色
    ctx.fillStyle = bgColor;
    ctx.fill();

    // 绘制圆角矩形背景（B和S共用逻辑）
    ctx.beginPath();
    ctx.moveTo(adjustedX + cornerRadius, drawY);
    ctx.arcTo(adjustedX + size, drawY, adjustedX + size, drawY + cornerRadius, cornerRadius);
    ctx.arcTo(adjustedX + size, drawY + size, adjustedX + size - cornerRadius, drawY + size, cornerRadius);
    ctx.arcTo(adjustedX, drawY + size, adjustedX, drawY + size - cornerRadius, cornerRadius);
    ctx.arcTo(adjustedX, drawY, adjustedX + cornerRadius, drawY, cornerRadius);
    ctx.closePath();
    ctx.fillStyle = bgColor;
    ctx.fill();

    // 绘制文字（居中显示）
    ctx.font = `${size * 0.6}px`;
    ctx.fillStyle = textColor;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText(text, adjustedX + size / 2, drawY + size / 2);
  },
  checkEventOn: (coordinate, attrs) => {
    const { x, y } = coordinate
    // console.log(x, y, attrs.x, attrs.y)
    return false
    // const { width, height } = attrs
    // return Math.abs(x * height) + Math.abs(y * width) <= width * height / 2
  }
})

registerOverlay({
  name: 'customOverlayCustomFigure',
  totalStep: 2,
  createPointFigures: ({ coordinates }) => {
    return {
      type: 'diamond',
      attrs: {
        x: coordinates[0].x,
        y: coordinates[0].y,
        size: 16,
        baseY: coordinates[0].y //60 
      },
      styles: {
        text: 'B'
        // bgColor: '#f6475d',
      }
    }
  },
})
registerOverlay({
  name: 'customOverlayCustomFigure1',
  totalStep: 2,
  createPointFigures: ({ coordinates }) => {
    return {
      type: 'diamond',
      attrs: {
        x: coordinates[0].x,
        y: coordinates[0].y,
        size: 16,
        baseY: coordinates[0].y //60 
      },
      styles: {
        text: 'S'
        // bgColor: '#f6475d',
      }
    }
  },
})
const uhx = ref({
  width: 0,
  height: 0
})
const isLoading = ref<boolean>(true)
const instance = getCurrentInstance()
let currencySocket: any
const currencyId = ref<string>()
const scrollContainer = ref<HTMLElement>()
const props = defineProps(['info'])
const weekList = ref([
  { title: '1分钟', value: 1, type: 'MINUTE' },
  { title: '5分钟', value: 5, type: 'MINUTE' },
  { title: '15分钟', value: 15, type: 'MINUTE' },
  { title: '30分钟', value: 30, type: 'MINUTE' },
  { title: '1小时', value: 1, type: 'HOUR' },
  { title: '4小时', value: 4, type: 'HOUR' },
  { title: '1天', value: 1, type: 'DAY' },
  // { title: '1周', value: 1, type: 'WEEK' },
])
interface CurrencyInfo {
  open: number;
  close: number;
  high: number;
  low: number;
  volume: number;
  time: string;
}

const currentInfo = ref<CurrencyInfo>({
  open: 0,
  close: 0,
  high: 0,
  low: 0,
  volume: 0,
  time: ''
})
const indicatorData = ref({})
const style = ref({})
const isContentOverflowValue = ref(false)
interface KlineItem {
  open: number;
  close: number;
  openTime: number;
  closeTime: number;
  lowest: number;
  highest: number;
  total: number;
  date: Date;
  timestamp: number;
};
const formatTimestampToDateTime = (timestamp: number, fallback = '暂无时间') => {
  let time = Number(timestamp);
  if (isNaN(time)) return fallback; // 非数字直接返回默认值
  if (time.toString().length === 10) {
    time *= 1000;
  }
  const date = new Date(time);
  if (date.toString() === 'Invalid Date') return fallback; // 无效时间返回默认值
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需 +1
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}/${month}/${day} ${hours}:${minutes}`;
};

const priceInfo = computed(() => {
  return useCoinStore().getPrice(useCoinStore().coinInfo.name)
})
const connectCurrency = () => {
  const item = weekList.value.find(item => item.title === useCoinStore().coinInfo.kLineType)
  const info = item ? item.value + item.type : '15MINUTE'
  if (currencyId.value) {
    currencySocket.unsubscribe(currencyId.value, `/topic/marketk/${useCoinStore().coinInfo.name}-USDT/${info}`)
  }
  currencyId.value = Date.now().toString(36) + Math.floor(Math.random() * 1000).toString(36)
  currencySocket.subscribe(currencyId.value, `/topic/marketk/${useCoinStore().coinInfo.name}-USDT/${info}`, (data: KlineItem) => {
    document.title = (priceInfo.value?.unitDecimals ? formatNumberWithThousands(data.close.toFixed(priceInfo.value?.unitDecimals)) : formatNumberWithThousands(data.close)) + ' | ' + useCoinStore().coinInfo.name + ' USDT | UHX'
    isLoading.value = false
    chart?.updateData({
      close: data.close,
      high: data.highest,
      low: data.lowest,
      open: data.open,
      timestamp: data.timestamp,
      volume: data.total
    })
    useCoinStore().setInfoPrice({
      close: data.close + '',
      high: data.highest + '',
      low: data.lowest + '',
      open: data.open + '',
      time: formatTimestampToDateTime(data.timestamp),
      volume: data.total + ''
    })
  })

}
let chart: any = null
const queryFn = async () => {
  const item = weekList.value.find(item => item.title === useCoinStore().coinInfo.kLineType)
  const data = await query({
    currencyPair: useCoinStore().coinInfo.name + '-USDT',
    timeType: item?.type || 'MINUTE',
    timeNumber: item?.value || 15,
    start: '0',
    stop: '1000'
  })

  return data
}
const changeWeek = async (type: string) => {
  isLoading.value = true
  chart.removeOverlay({ name: 'customOverlayCustomFigure' })
  chart.removeOverlay({ name: 'customOverlayCustomFigure1' })
  useCoinStore().setCoinKlineType(type)
  connectCurrency()
  const data = await queryFn()
  const list = data.map(item => {
    return {
      close: item.close,
      high: item.highest,
      low: item.lowest,
      open: item.open,
      timestamp: item.timestamp,
      volume: item.total
    }
  })
  chart?.applyNewData(list)
  const item = weekList.value.find(item => item.title === useCoinStore().coinInfo.kLineType)
  const typeInfo = (item?.value || 15) + (item?.type || 'MINUTE') as TimeType
  const buyList = userStore().userOrderInfo.buy[useCoinStore().coinInfo.name] || []
  const sellList = userStore().userOrderInfo.sell[useCoinStore().coinInfo.name] || []
  buyList.forEach((item: any) => {
    const data = getFloorPeriodTimestamps(item.time)
    chart.createOverlay({
      id: data[typeInfo],
      name: 'customOverlayCustomFigure',
      points: [{ timestamp: data[typeInfo], value: Number(item.price), dataIndex: 100 },],
    }, 'chart')
  })
  sellList.forEach((item: any) => {
    const data = getFloorPeriodTimestamps(Number(item.time))
    chart.createOverlay({
      id: data[typeInfo],
      name: 'customOverlayCustomFigure1',
      points: [{ timestamp: data[typeInfo], value: Number(item.price), dataIndex: 100 }]
    }, 'chart')
  })
}
const isContentOverflow = () => {
  if (!scrollContainer.value) return false;
  const container = scrollContainer.value;
  const containerWidth = container.clientWidth;
  const children = container.children as unknown as HTMLElement[];
  let totalChildrenWidth = 0;
  for (let i = 0; i < children.length; i++) {
    totalChildrenWidth += children[i].offsetWidth;
  }
  totalChildrenWidth += (children.length - 1) * 10;
  isContentOverflowValue.value = totalChildrenWidth > containerWidth;
};
const width = ref('')
const indicator = ref({
  vol: 0,
  macd: 0,
})
onMounted(async () => {
  useCoinStore().setInCharts(false)
  const data = await queryFn()
  const list = data.map(item => {
    return {
      close: item.close,
      high: item.highest,
      low: item.lowest,
      open: item.open,
      timestamp: item.timestamp,
      volume: item.total
    }
  })
  chart = init('chart', {
    styles: {
      // 蜡烛图
      candle: {
        bar: {
          upColor: useSettingsStore().greenRise ? '#2dbd85' : '#f6475d',
          downColor: useSettingsStore().greenRise ? '#f6475d' : '#2dbd85',
          noChangeColor: useSettingsStore().greenRise ? '#2dbd85' : '#f6475d',
          upBorderColor: useSettingsStore().greenRise ? '#2dbd85' : '#f6475d',
          downBorderColor: useSettingsStore().greenRise ? '#f6475d' : '#2dbd85',
          noChangeBorderColor: useSettingsStore().greenRise ? '#2dbd85' : '#f6475d',
          upWickColor: useSettingsStore().greenRise ? '#2dbd85' : '#f6475d',
          downWickColor: useSettingsStore().greenRise ? '#f6475d' : '#2dbd85',
          noChangeWickColor: useSettingsStore().greenRise ? '#2dbd85' : '#f6475d',
        },
        priceMark: {
          high: {
            textOffset: 5,
          },
          last: {
            upColor: useSettingsStore().greenRise ? '#2dbd85' : '#f6475d',
            downColor: useSettingsStore().greenRise ? '#f6475d' : '#2dbd85',
            noChangeColor: '#888888'
          }
        },
        tooltip: {
          offsetTop: 0,
          offsetLeft: -8,
        }
      },
      indicator: {
        bars: [
          {
            borderSize: 1,
            borderDashedValue: [2, 2],
            upColor: useSettingsStore().greenRise ? '#2dbd85' : '#f6475d',
            downColor: useSettingsStore().greenRise ? '#f6475d' : '#2dbd85',
            noChangeColor: '#888888'
          }
        ]
      },
      grid: {
        horizontal: {
          color: useThemeStore().theme === 'dark' ? '#22282f' : '#ededed',
        },
        vertical: {
          color: useThemeStore().theme === 'dark' ? '#22282f' : '#ededed',
        },
      },
      yAxis: {
        tickLine: {
          show: false,
        },
        axisLine: {
          size: 1,
          color: useThemeStore().theme === 'dark' ? '#333b47' : '#ededed',
        },
      },
      separator: {
        color: useThemeStore().theme === 'dark' ? '#333b47' : '#ededed',
      },
      xAxis: {
        tickLine: {
          show: false,
        },
        axisLine: {
          color: useThemeStore().theme === 'dark' ? '#333b47' : '#ededed',
        },
      },
      crosshair: {
        horizontal: {
          text: {
            color: useThemeStore().theme === 'dark' ? '#fff' : '#000',
            backgroundColor: useThemeStore().theme === 'dark' ? '#434c5a' : '#dddddd'
          }
        },
        vertical: {
          text: {
            color: useThemeStore().theme === 'dark' ? '#fff' : '#000',
            backgroundColor: useThemeStore().theme === 'dark' ? '#434c5a' : '#dddddd'
          }
        }
      }
    },
  })
  chart.setStyles({
    candle: {
      tooltip: {
        showRule: 'none'
      }
    },
    indicator: {
      tooltip: {
        showRule: 'none'
      }
    }
  })

  chart.setBarSpace(7)
  chart.applyNewData(list)
  chart.setPriceVolumePrecision(useCoinStore().getPrice(useCoinStore().coinInfo.name)?.unitDecimals)
  chart.setLeftMinVisibleBarCount(9)
  chart.setOffsetRightDistance(54)
  registerIndicatorMa()
  registerIndicatorEma()
  registerIndicatoVol()
  registerIndicatoMacd()
  chart.subscribeAction('onCrosshairChange', (e: any) => {
    const data = e.kLineData
    indicatorData.value = e.indicatorData
    useCoinStore().setInCharts(true)
    data.time = formatTimestampToDateTime(data.timestamp)
    currentInfo.value = data
  })
  // chart.createOverlay({
  //   name: 'priceLine',
  //   lock: true,
  //   points: [
  //     {  value: 115000 },
  //   ],
  // })
  // chart.createOverlay({
  //   name: 'simpleTag',
  //   points: [{ timestamp: 1614171282000, value: 115000 }], // 从该点向右无限延伸
  //   color: '#2dbd85'
  // });
  chart.subscribeAction('onPaneDrag', () => {
    setTimeout(() => {
      uhx.value = {
        width: chart?.getSize('candle_pane', 'main').width,
        height: chart?.getSize('candle_pane', 'main').height,
      }
      indicator.value.vol = chart?.getSize('VOL')?.top || 0
      indicator.value.macd = chart?.getSize('MACD')?.top || 0
    }, 0);
  })
  chart.setLocale('zh-CN')
  if (userStore().mainIndicator.ma.checked) {
    chart.createIndicator({
      name: 'MA',
      visible: userStore().mainIndicator.ma.hide,
    }, true, { id: 'candle_pane' })
  }
  if (userStore().mainIndicator.ema.checked) {
    chart.createIndicator({
      name: 'EMA',
      visible: userStore().mainIndicator.ema.hide,
    }, true, { id: 'candle_pane' })
  }
  if (userStore().mainIndicator.vol.checked) {
    chart.createIndicator({ name: 'VOL', precision: 2 }, true, {
      id: 'VOL',
      height: 100,
    })
    setTimeout(() => {
      indicator.value.vol = chart?.getSize('VOL')?.top || 0
      indicator.value.macd = chart?.getSize('MACD')?.top || 0
    }, 100);
  }
  if (userStore().mainIndicator.macd.checked) {
    chart.createIndicator({ name: 'MACD', precision: 2 }, true, {
      id: 'MACD',
      height: 100,
    })
    setTimeout(() => {
      indicator.value.vol = chart?.getSize('VOL')?.top || 0
      indicator.value.macd = chart?.getSize('MACD')?.top || 0
    }, 100);
  }

  const buyList = userStore().userOrderInfo.buy[useCoinStore().coinInfo.name] || []
  const sellList = userStore().userOrderInfo.sell[useCoinStore().coinInfo.name] || []
  const item = weekList.value.find(item => item.title === useCoinStore().coinInfo.kLineType)
  const type = (item?.value || 15) + (item?.type || 'MINUTE') as TimeType
  sellList.forEach((item: any) => {
    const data = getFloorPeriodTimestamps(Number(item.time))
    chart.createOverlay({
      id: data[type],
      name: 'customOverlayCustomFigure1',
      points: [{ timestamp: data[type], value: Number(item.price), dataIndex: 100 }]
    }, 'chart')
  })
  buyList.forEach((item: any) => {
    const data = getFloorPeriodTimestamps(Number(item.time))
    chart.createOverlay({
      id: data[type],
      name: 'customOverlayCustomFigure',
      points: [{ timestamp: data[type], value: Number(item.price), dataIndex: 100 }]
    }, 'chart')
  })
  width.value = (chart?.getSize('candle_pane', 'main')?.width - 14) + 'px'
  setTimeout(() => {
    isContentOverflow()
  }, 0);
})
watch(() => userStore().currencySocket, async (val) => {
  if (val) {
    const data = await queryFn()
    const list = data.map(item => {
      return {
        close: item.close,
        high: item.highest,
        low: item.lowest,
        open: item.open,
        timestamp: item.timestamp,
        volume: item.total
      }
    })
    chart?.applyNewData(list)
    if (instance) {
      currencySocket = instance.appContext.config.globalProperties.$currencySocket
      if (currencySocket.connected) {
        connectCurrency()
      }
    }
  }
}, { immediate: true })

watch(() => userStore().mainIndicator.vol.checked, (v, o) => {
  if (v) {
    registerIndicatoVol()
    chart.removeIndicator('VOL')
    chart.createIndicator({ name: 'VOL', precision: 2 }, true, {
      id: 'VOL'
    })
  } else {
    chart.removeIndicator('VOL')
  }

  setTimeout(() => {
    uhx.value = {
      width: chart?.getSize('candle_pane', 'main').width,
      height: chart?.getSize('candle_pane', 'main').height,
    }
    indicator.value.vol = chart?.getSize('VOL')?.top || 0
    indicator.value.macd = chart?.getSize('MACD')?.top || 0
  }, 0);
})
watch(() => userStore().mainIndicator.macd.checked, (v, o) => {
  if (v) {
    registerIndicatoMacd()
    chart.removeIndicator('MACD')
    chart.createIndicator({ name: 'MACD', precision: 2 }, true, {
      id: 'MACD'
    })
  } else {
    chart.removeIndicator('MACD')
  }
  setTimeout(() => {
    uhx.value = {
      width: chart?.getSize('candle_pane', 'main').width,
      height: chart?.getSize('candle_pane', 'main').height,
    }
    indicator.value.vol = chart?.getSize('VOL')?.top || 0
    indicator.value.macd = chart?.getSize('MACD')?.top || 0
  }, 0);
})
watch(() => userStore().mainIndicator.vol.list, (v, o) => {
  if (userStore().mainIndicator.vol.checked) {
    const calcParams = userStore().mainIndicator.vol.list.filter((item: any) => item.checked).map((item: any) => item.value)
    const figures = userStore().mainIndicator.vol.list.filter((item: any) => item.checked).map((item: any) => {
      const obj = {
        key: item.key,
        title: item.title,
        type: 'line',
        styles: () => {
          return { color: item.color, size: item.lineSize * 0.5 }
        }
      }
      obj.key = `VOLMA(${item.value})`
      return obj
    })
    registerIndicatoVol()
    chart.overrideIndicator({
      name: 'VOL',
      calcParams,
      figures: [...figures, {
        key: 'vol', title: 'VOL: ', type: 'bar', styles: (data: any) => {
          const data1 = data.current?.kLineData;
          if (data1?.close && data1?.open && data1.close > data1.open) {
            return { color: '#34bf88', borderColor: '#34bf88', style: userStore().mainIndicator.vol.barType.long };
          }
          return { color: '#f6465d', borderColor: '#f6465d', style: userStore().mainIndicator.vol.barType.short };
        }
      }],
    })
  }
})
watch(() => userStore().mainIndicator.macd, (v, o) => {
  if (userStore().mainIndicator.macd.checked) {
    const calcParams = userStore().mainIndicator.macd.periodList.map((item: any) => Number(item.value))
    const figures = userStore().mainIndicator.macd.list.filter((item: any) => item.checked).map((item: any) => {
      const obj: any = {
        key: item.title,
        title: item.title,
        type: 'line',
        baseValue: 0,
        styles: () => {
          return {}
        }
      }
      if (item.code === 'macd') {
        obj.type = 'bar'
        obj.styles = (data: any) => {
          const { prev, current } = data
          const prevMacd = prev?.indicatorData?.MACD ?? Number.MIN_SAFE_INTEGER
          const currentMacd = current?.indicatorData?.MACD ?? Number.MIN_SAFE_INTEGER
          let color = ''
          let style = ''
          //long
          if (currentMacd >= 0) {
            if (prevMacd < currentMacd) {
              color = userStore().mainIndicator.macd.type.LongGrow.color
              style = userStore().mainIndicator.macd.type.LongGrow.type
            } else {
              color = userStore().mainIndicator.macd.type.LongFall.color
              style = userStore().mainIndicator.macd.type.LongFall.type
            }
          } else if (currentMacd < 0) {
            if (prevMacd < currentMacd) {
              color = userStore().mainIndicator.macd.type.ShortGrow.color
              style = userStore().mainIndicator.macd.type.ShortGrow.type
            } else {
              color = userStore().mainIndicator.macd.type.ShortFall.color
              style = userStore().mainIndicator.macd.type.ShortFall.type
            }
          }
          return { style, color, borderColor: color }
        }

      } else {
        obj.styles = () => {
          return { color: item.color, size: item.lineSize }
        }

      }
      return obj
    })
    registerIndicatoMacd()
    chart.overrideIndicator({
      name: 'MACD',
      calcParams,
      figures,
    })
  }
})
watch(() => userStore().mainIndicator.ma.checked, (v, o) => {
  if (v) {
    registerIndicatorMa()
    chart.removeIndicator('candle_pane', 'MA')
    chart.createIndicator({
      name: 'MA',
      visible: userStore().mainIndicator.ma.hide,
    }, true, { id: 'candle_pane' })
  } else {
    chart.removeIndicator('candle_pane', 'MA')
  }
})
watch(() => userStore().mainIndicator.ma.list, (v, o) => {
  if (userStore().mainIndicator.ma.checked) {
    registerIndicatorMa()
    chart.removeIndicator('candle_pane', 'MA')
    chart.createIndicator({
      name: 'MA',
      visible: userStore().mainIndicator.ma.hide,
    }, true, { id: 'candle_pane' })
  }
})
watch(() => userStore().mainIndicator.ma.hide, (v, o) => {
  chart.overrideIndicator({
    name: 'MA',
    visible: userStore().mainIndicator.ma.hide,
  })
})
watch(() => userStore().mainIndicator.vol.hide, (v, o) => {
  chart.overrideIndicator({
    name: 'VOL',
    visible: userStore().mainIndicator.vol.hide,
  })
})
watch(() => userStore().mainIndicator.macd.hide, (v, o) => {
  chart.overrideIndicator({
    name: 'MACD',
    visible: userStore().mainIndicator.macd.hide,
  })
})
watch(() => userStore().mainIndicator.ema.checked, (v, o) => {
  if (v) {
    registerIndicatorEma()
    chart.removeIndicator('candle_pane', 'EMA')
    chart.createIndicator({
      name: 'EMA',
      visible: userStore().mainIndicator.ema.hide,
    }, true, { id: 'candle_pane' })
  } else {
    chart.removeIndicator('candle_pane', 'EMA')
  }
})
watch(() => userStore().mainIndicator.ema.list, (v, o) => {
  if (userStore().mainIndicator.ema.checked) {
    registerIndicatorEma()
    chart.removeIndicator('candle_pane', 'EMA')
    chart.createIndicator({
      name: 'EMA',
      visible: userStore().mainIndicator.ema.hide,
    }, true, { id: 'candle_pane' })
  }
})
watch(() => userStore().mainIndicator.ema.hide, (v, o) => {
  chart.overrideIndicator({
    name: 'EMA',
    visible: userStore().mainIndicator.ema.hide,
  })
})
watch(() => props.info, (v) => {
  style.value = {
    width: v.width - 32 + 'px',
    height: v.height - 81 + 'px'
  }
  setTimeout(() => {
    chart?.resize()
  }, 100);
  setTimeout(() => {
    width.value = (chart?.getSize('candle_pane', 'main').width - 14) + 'px'
  }, 200);
  setTimeout(() => {
    uhx.value = {
      width: chart?.getSize('candle_pane', 'main').width,
      height: chart?.getSize('candle_pane', 'main').height,
    }
    indicator.value.vol = chart?.getSize('VOL')?.top || 0
    indicator.value.macd = chart?.getSize('MACD')?.top || 0
  }, 500);
}, {
  deep: true, // 若为对象/数组需开启深度监听
  immediate: true // 关键：立即执行一次
})
watch(() => useCoinStore().coinInfo.name, async (v) => {
  chart.removeOverlay({ name: 'customOverlayCustomFigure' })
  chart.removeOverlay({ name: 'customOverlayCustomFigure1' })
  isLoading.value = true
  connectCurrency()
  const data = await queryFn()
  const list = data.map(item => {
    return {
      close: item.close,
      high: item.highest,
      low: item.lowest,
      open: item.open,
      timestamp: item.timestamp,
      volume: item.total
    }
  })
  chart.setPriceVolumePrecision(useCoinStore().getPrice(useCoinStore().coinInfo.name)?.unitDecimals, 2)
  chart?.applyNewData(list)
  const buyList = userStore().userOrderInfo.buy[useCoinStore().coinInfo.name] || []
  const sellList = userStore().userOrderInfo.sell[useCoinStore().coinInfo.name] || []
  const item = weekList.value.find(item => item.title === useCoinStore().coinInfo.kLineType)
  const type = (item?.value || 15) + (item?.type || 'MINUTE') as TimeType
  sellList.forEach((item: any) => {
    const data = getFloorPeriodTimestamps(Number(item.time))
    chart.createOverlay({
      id: data[type],
      name: 'customOverlayCustomFigure1',
      points: [{ timestamp: data[type], value: Number(item.price), dataIndex: 100 }]
    }, 'chart')
  })
  buyList.forEach((item: any) => {
    const data = getFloorPeriodTimestamps(Number(item.time))
    chart.createOverlay({
      id: data[type],
      name: 'customOverlayCustomFigure',
      points: [{ timestamp: data[type], value: Number(item.price), dataIndex: 100 }]
    }, 'chart')
  })

})
type TimeType = '1MINUTE' | '5MINUTE' | '15MINUTE' | '1HOUR' | '1DAY' | '1WEEK';

watch(() => userStore().sellStatus, (v) => {
  if (v) {
    const time = new Date().getTime()
    const sellList = userStore().userOrderInfo.sell[useCoinStore().coinInfo.name] || []
    sellList.push({ price: Number(v), time })
    userStore().setUserOrderInfo('sell', useCoinStore().coinInfo.name, sellList)
    setTimeout(() => {
      userStore().setSellStatus(0)
    }, 0);
    const item = weekList.value.find(item => item.title === useCoinStore().coinInfo.kLineType)
    const type = (item?.value || 15) + (item?.type || 'MINUTE') as TimeType
    const data = getFloorPeriodTimestamps(time)
    chart.createOverlay({
      id: time,
      name: 'customOverlayCustomFigure1',
      zIndex: 100,
      lock: true,
      points: [{ timestamp: data[type], value: Number(v), dataIndex: 2 },],
    }, 'chart')
  }
})
watch(() => userStore().buyStatus, (v) => {
  if (v) {
    const time = new Date().getTime()
    const buyList = userStore().userOrderInfo.buy[useCoinStore().coinInfo.name] || []
    buyList.push({ price: Number(v), time })
    userStore().setUserOrderInfo('buy', useCoinStore().coinInfo.name, buyList)
    setTimeout(() => {
      userStore().setBuyStatus(0)
    }, 0);
    const item = weekList.value.find(item => item.title === useCoinStore().coinInfo.kLineType)
    const type = (item?.value || 15) + (item?.type || 'MINUTE') as TimeType
    const data = getFloorPeriodTimestamps(time)
    chart.createOverlay({
      id: time,
      name: 'customOverlayCustomFigure',
      zIndex: 100,
      lock: true,
      points: [{ timestamp: data[type], value: Number(v), dataIndex: 2 },],
    }, 'chart')
  }
})

watch(() => useThemeStore().theme, (v) => {
  chart?.setStyles({
    grid: {
      horizontal: {
        color: v === 'dark' ? '#22282f' : '#ededed',
      },
      vertical: {
        color: v === 'dark' ? '#22282f' : '#ededed',
      },
    },
    yAxis: {
      axisLine: {
        size: 1,
        color: v === 'dark' ? '#333b47' : '#ededed',
      },
    },
    separator: {
      color: v === 'dark' ? '#333b47' : '#ededed',
    },
    xAxis: {
      axisLine: {
        color: v === 'dark' ? '#333b47' : '#ededed',
      },
    },
    crosshair: {
      horizontal: {
        text: {
          color: v === 'dark' ? '#fff' : '#000',
          backgroundColor: v === 'dark' ? '#333b47' : '#dddddd'
        }
      },
      vertical: {
        text: {
          color: v === 'dark' ? '#fff' : '#000',
          backgroundColor: v === 'dark' ? '#333b47' : '#dddddd'
        }
      }
    }
  })
})

watch(() => useSettingsStore().greenRise, (v) => {
  chart?.setStyles({
    candle: {
      bar: {
        upColor: useSettingsStore().greenRise ? '#2dbd85' : '#f6475d',
        downColor: useSettingsStore().greenRise ? '#f6475d' : '#2dbd85',
        noChangeColor: useSettingsStore().greenRise ? '#2dbd85' : '#f6475d',
        upBorderColor: useSettingsStore().greenRise ? '#2dbd85' : '#f6475d',
        downBorderColor: useSettingsStore().greenRise ? '#f6475d' : '#2dbd85',
        noChangeBorderColor: useSettingsStore().greenRise ? '#2dbd85' : '#f6475d',
        upWickColor: useSettingsStore().greenRise ? '#2dbd85' : '#f6475d',
        downWickColor: useSettingsStore().greenRise ? '#f6475d' : '#2dbd85',
        noChangeWickColor: useSettingsStore().greenRise ? '#2dbd85' : '#f6475d',
      },
      priceMark: {
        high: {
          textOffset: 5,
        },
        last: {
          upColor: useSettingsStore().greenRise ? '#2dbd85' : '#f6475d',
          downColor: useSettingsStore().greenRise ? '#f6475d' : '#2dbd85',
          noChangeColor: '#888888'
        }
      },
      tooltip: {
        offsetTop: 0,
        offsetLeft: -8,
      }
    },
  })
})
const mouseenterFn = () => {
  useCoinStore().setInCharts(false)
}

const emit = defineEmits(['showindicator'])
const showindicator = (e: string, x: string) => {
  emit('showindicator', e, x)
}
const mouseEnter = () => {
  useCoinStore().setInCharts(false)
}
const mouseLeave = () => {
  useCoinStore().setInCharts(false)
}
onUnmounted(() => {
  const item = weekList.value.find(item => item.title === useCoinStore().coinInfo.kLineType)
  const info = item ? item.value + item.type : '15MINUTE'
  if (currencySocket) {
    currencySocket.unsubscribe(currencyId.value, `/topic/marketk/${useCoinStore().coinInfo.name}-USDT/${info}`)
  }
  dispose('chart')
})

</script>

<template>
  <div>
    <div v-show="!isLoading" class="h-[20px] my-[10px] text-[12px] flex items-center text-gray-400 dark:text-[#707A8A]">
      <div class="w-[400px] cursor-pointer overflow-hidden flex flex-nowrap gap-[10px] items-center h-[20px]"
        ref="scrollContainer">
        <div class="flex-shrink-0" v-show="isContentOverflowValue"></div>
        <div @click="changeWeek(item.title)"
          :class="[item.title === useCoinStore().coinInfo.kLineType ? 'text-black dark:text-[#eaecef]' : '']"
          v-for="item, i in weekList" :key="i" class=" flex-shrink-0 ">{{ item.title }}</div>
        <ElTooltip content="技术指标" placement="top">
          <div class="iconfont icon-jishuzhibiao" @click="showindicator('', 'main')"></div>
        </ElTooltip>
        <div class="iconfont icon-shezhi"></div>
      </div>
    </div>
    <div id="chart" :style="style" class="relative" @mouseenter="mouseEnter" @mouseleave="mouseLeave">
      <div v-show="uhx.height && uhx.width"
        class=" absolute left-0 top-0 flex dark:text-[#202228] items-center justify-center text-[60px] font-bold text-[#f6f6f7]"
        :style="{ width: uhx.width + 'px', height: uhx.height + 'px' }">UHX</div>
      <div class=" absolute left-0 top-0 text-[12px] z-[20]" @mouseenter="mouseenterFn">
        <TootipOrdinary :currentInfo="currentInfo" :width="width" />
        <TootipMA @setMainIndicator="showindicator" v-if="userStore().mainIndicator.ma.checked"
          :currentInfo="indicatorData" :width="width" />
        <TootipEMA @setMainIndicator="showindicator" v-if="userStore().mainIndicator.ema.checked"
          :currentInfo="indicatorData" :width="width" />
      </div>
      <div @mouseenter="mouseenterFn" class=" absolute left-0 z-[20] text-[12px] p-[4px]"
        v-if="userStore().mainIndicator.vol.checked" :style="{ top: indicator.vol + 5 + 'px' }">
        <TootipVOL @setMainIndicator="showindicator"
          v-if="!userStore().mainIndicator.vol.hiden && userStore().mainIndicator.vol.checked"
          :currentInfo="indicatorData" :width="width" />
      </div>
      <div @mouseenter="mouseenterFn" class=" absolute left-0 z-[20] text-[12px] p-[4px]"
        v-if="userStore().mainIndicator.macd.checked" :style="{ top: indicator.macd + 5 + 'px' }">
        <TootipMACD @setMainIndicator="showindicator"
          v-if="!userStore().mainIndicator.macd.hiden && userStore().mainIndicator.macd.checked"
          :currentInfo="indicatorData" :info="currentInfo" :width="width" />
      </div>
      <div v-show="isLoading" :style="style"
        class="flex left-0 top-0 justify-center items-center absolute z-[999] bg-[#ffffff] dark:bg-[#181a21]">
        <Loading />
      </div>
    </div>

  </div>
</template>